import axios from "axios";
// import { Message } from "@arco-design/web-vue";
import { useUserStore } from "@/stores";

const baseURL = import.meta.env.VITE_APP_BASE_URL;

// 创建axios实例
const service = axios.create({
	// 根据不同env设置不同的baseURL
	baseURL: baseURL,
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 5000, // request timeout
});

// axios实例拦截请求
service.interceptors.request.use(
	(config) => {
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

// axios实例拦截响应
service.interceptors.response.use(
	// 2xx时触发
	(response) => {
		// response.data就是后端返回的数据，结构根据你们的约定来定义
		const { status, data } = response;

		// if (success) {
		// 	return response;
		// }

		if (status === 200) {
			return data;
		}

		return Promise.reject(data);
	},
	// 非2xx时触发
	(error) => {
		return Promise.reject(error);
	}
);

export const request = ({ url, params = {}, method = "GET", data = {} }) => {
	return new Promise((resolve, reject) => {
		const userStore = useUserStore();

		// console.log(userStore.token)

		return service
			.request({
				url,
				params,
				data,
				method,
				// headers: {
				// 	Authorization: userStore.getToken,
				// },
			})
			.then((res) => {
				resolve(res);
			})
			.catch((err) => {
				console.error("request fail: " + err.message);
				// Message.error("request fail: " + err.message);
			});
	});
};
